/**
 * 通过基于类对象的同步语句块进行线程同步的例程
 * 说明类的实例对象与静态成员域之间的关系
 */
package thread;

public class J_BlockClass extends Thread {
    public static int m_data = 0;
    public static int m_times = 1000;
    public int m_ID;
    public boolean m_done;

    J_BlockClass(int id) {
        m_ID = id;
    }

    @Override
    public void run() {
        m_done = false;
        int d = ((m_ID % 2 == 0) ? 1 : -1);
        System.out.printf("运行线程： %1$d 增量为：%2$d \r\n", m_ID, d);
        try {
            System.out.println("" + J_BlockClass.class.hashCode());
            System.out.println("" + Class.forName("thread.J_BlockClass").hashCode());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        synchronized (J_BlockClass.class) {
//        synchronized (this){//this所指向的当前实例对象会发生变化
            System.out.printf("线程： %1$d 进入同步语句块 m_data：%2$d \r\n", m_ID, m_data);
            for (int i = 0; i < m_times; i++) {
                for (int j = 0; j < m_times; j++) {
                    m_data += d;
                }
            }
            System.out.printf("线程： %1$d 离开同步语句块 m_data：%2$d \r\n", m_ID, m_data);
        }

        m_done = true;
        System.out.println("结束线程：" + m_ID);
    }

    public static void main(String args[]) {
        J_BlockClass t1 = new J_BlockClass(1);
        J_BlockClass t2 = new J_BlockClass(2);
        t1.m_done = false;
        t2.m_done = false;
        t1.start();
        t2.start();
        while (!t1.m_done || !t2.m_done) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("结果：m_data=" + m_data);
    }
}
